package com.dc.base.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.dc.base.viewmodel.BaseViewModel;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

/**
 * @author 冰柠檬dc
 */
public abstract class BaseVmVbFragment<VM extends BaseViewModel, VB extends ViewBinding> extends BaseVmFragment<VM> {

    protected VB mViewBinding;

    @Override
    protected int layoutId() {
        return 0;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mViewBinding = getViewBinding(inflater, container);
        return mViewBinding == null ? super.onCreateView(inflater, container, savedInstanceState) : mViewBinding.getRoot();
    }

    protected VB getViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class cls = (Class) type.getActualTypeArguments()[1];
        try {
            Method inflate = cls.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
            return (VB) inflate.invoke(null, inflater, container, false);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 非反射获取VB(子类中实现，如FragmentFirstBinding.inflate(inflater, container, false))
     */
//    protected abstract VB getViewBinding(LayoutInflater inflater, ViewGroup container);
}
